import { ref, onMounted, onUnmounted } from "vue";
import { ElMessageBox } from "element-plus";
import { useUserStoreHook } from "@/store/modules/user";
import { getToken, formatToken } from "@/utils/auth";
import { subscribe } from "@/swagger/api/monitor";
const { VITE_GLOBAL_API_URL } = import.meta.env;

export function useKickSSE() {
  const eventSource = ref<EventSource | null>(null);

  const startSSE = () => {
    const token = getToken(); // 根据你的 token 存储方式
    if (!token) {
      console.error("token 不存在");
      return;
    }
    // SSE URL 可以带 token/tenantId 作为查询参数
    const url = `${VITE_GLOBAL_API_URL}/api/monitor/subscribe?access_token=${token.accessToken}`;

    eventSource.value = new EventSource(url);

    // 接收踢人事件
    eventSource.value.addEventListener("kick", (event: MessageEvent) => {
      ElMessageBox.alert(event.data, "提示", {
        confirmButtonText: "确定",
        callback: () => {
          localStorage.clear(); // 清空 token
          useUserStoreHook().logOut();
        }
      });
    });

    // 可选：监听连接错误，自动重连
    eventSource.value.onerror = () => {
      console.warn("SSE连接异常，尝试重连...");
      eventSource.value?.close();
      setTimeout(startSSE, 3000); // 3秒后重连
    };
  };

  onMounted(() => {
    startSSE();
  });

  onUnmounted(() => {
    eventSource.value?.close();
  });

  return {
    eventSource
  };
}